package com.ken.work.apache.mina;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;
import org.apache.mina.http.HttpServerCodec;
import org.apache.mina.http.HttpServerDecoder;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class HttpServer {
	private static final Logger LOG = Logger.getLogger(HttpServer.class);
	private static int PORT = 5000;

	private static HttpServer aTcpServer=null;
	private HttpServer(){}
	public static HttpServer getInstance()
	{
		if(aTcpServer==null)
			aTcpServer=new HttpServer();
		return aTcpServer;
	}
	public void start(int port) {
		try {
			PORT=port;
			@SuppressWarnings("static-access")
			// 创建一个非阻塞的server端的Socket
			IoAcceptor acceptor = new NioSocketAcceptor();
			acceptor.getFilterChain().addLast("codec", new HttpServerCodec());
			// acceptor.getFilterChain().addLast("logger", new LoggingFilter());
			// 不设置过滤器（使用 Mina提供的文本换行符编解码器）
			// 设置读取数据的缓冲区大小
			acceptor.getSessionConfig().setReadBufferSize(8384);
			// 读写通道10秒内无操作进入空闲状态
			acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
			acceptor.getSessionConfig().setWriteTimeout(10);
			// 绑定逻辑处理器
			acceptor.setHandler(new HttpServerHandler());
			// 绑定端口
			acceptor.bind(new InetSocketAddress(PORT));
			LOG.info("服务端启动成功...     端口号为：" + PORT);

		} catch (Exception e) {
			LOG.error("Mina服务端启动异常....", e);
			e.printStackTrace();
		}
	}
	 
}
